import 'antd/dist/antd.css'
import './App.css'

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Table, Select, AutoComplete, Checkbox } from 'antd';

const { Option } = Select;

import dataURL from './data/大采集_std.csv';
import categoryURL from './data/分类列表_std.csv';
import AttrIcon from "./components/AttrIcon";
import WeatherIcon from "./components/WeatherIcon";
import NameFinder from "./components/NameFinder";
import BooleanCheckbox from "./components/BooleanCheckbox";

function parseCSV(str) {
  const row = str.split('\n').map(r => r.split(','));
  const header = row[0];
  return row.slice(1).map(r => {
    const obj = {};
    header.forEach((key, index) => {
      obj[key] = r[index];
    });
    return obj;
  });
}

function useStateWithRef(initVal) {
  const [val, setVal] = useState(initVal);
  const vRef = useRef(initVal);

  const outerSetValue = useMemo(() => {
    return (v) => {
      vRef.current = v;
      setVal(v);
    }
  }, []);

  return [val, outerSetValue, vRef];
}

function useUpdate(setQuery, queryRef, updateKey) {
  return useCallback((val) => {
    setQuery({
      ...queryRef.current,
      [updateKey]: val,
    });
  }, []);
}

function App() {

  const [data, setData] = useState([]);
  const [result, setResult] = useState([]);
  const [query, setQuery, queryRef] = useStateWithRef({
    attr: -1,
    category: -1,
    keywords: '',

    skipSickle: false,
    skipPickaxe: false,
    skipHammer: false,
  });

  const attrList = useMemo(() => ['风', '火', '冰', '电', '光'], []);
  const [categoryList, setcategoryList] = useState([]);

  const updateAttr = useUpdate(setQuery, queryRef, 'attr');
  const updateCategory = useUpdate(setQuery, queryRef, 'category');
  const updateKeywords = useUpdate(setQuery, queryRef, 'keywords');

  const updateTS = useUpdate(setQuery, queryRef, 'skipSickle');
  const updateTP = useUpdate(setQuery, queryRef, 'skipPickaxe');
  const updateTH = useUpdate(setQuery, queryRef, 'skipHammer');

  useEffect(() => {

    if (query.attr === -1
      && query.category === -1
      && query.keywords === ''
      && ((query.skipSickle || query.skipPickaxe || query.skipHammer) === false)
    ) {
      setResult(data.concat())

      return;
    }

    setResult(data.filter(row => {
      if (query.attr !== -1) {
        if (Number(row.mainAttrId) !== query.attr) return false;
      }

      if (query.category !== -1) {
        if (!row['类型'].match(query.category)) return false;
      }

      if (query.keywords) {
        if (!row['素材'].match(query.keywords)) return false;
      }

      if (query.skipSickle) {
        if (row['工具'] === '镰刀') return false;
      }

      if (query.skipPickaxe) {
        if (row['工具'] === '镐头') return false;
      }

      if (query.skipHammer) {
        if (row['工具'] === '爆破锤') return false;
      }

      return true;
    }))
  }, [data, query]);

  useEffect(() => {
    Promise.all([
      fetch(dataURL).then(res => res.text()),
      fetch(categoryURL).then(res => res.text()),
    ]).then(([s, c]) => {

      const data = parseCSV(s);
      const category = parseCSV(c);

      setData(data);
      setResult(data.concat());
      setcategoryList(category);
    });
  }, []);

  const columns = useMemo(() => {
    return ['地图', '工具', '天气', '星数', '素材', '主属性', '类型'].map((name) => {

      const base = {
        title: name,
        dataIndex: name,
        key: name,
      };

      if (name === '天气') {
        base.render = (_, record) => {
          return <WeatherIcon key={record.weatherId} attr={record.weatherId}/>
        }
      }

      if (name === '主属性') {
        base.render = (_, record) => {
          return <AttrIcon key={record.mainAttrId} attr={record.mainAttrId}/>
        }
      }

      return base;
    });
  }, [data]);

  return (
    <div className="App">
      <div className="query-area">

        <div className="query-row">
          <div className="query-item">
            <div>主属性</div>
            <Select onChange={updateAttr} defaultValue={-1}>
              <Option value={-1}>随意</Option>
              {attrList.map((a, i) => (<Option value={i} key={i}>{a}</Option>))}
            </Select>
          </div>

          <div className="query-item">
            <div>分类</div>
            <Select onChange={updateCategory} defaultValue={-1}>
              <Option value={-1}>随意</Option>
              {categoryList.map((c) => (<Option value={c['类型']} key={c['类型']}>{c['类型']}</Option>))}
            </Select>
          </div>

          <div className="query-item">
            <div>分类</div>
            <Select onChange={updateCategory} defaultValue={-1}>
              <Option value={-1}>随意</Option>
              {categoryList.map((c) => (<Option value={c['类型']} key={c['类型']}>{c['类型']}</Option>))}
            </Select>
          </div>

          <div className="query-item">
            <div>快速搜索</div>
            <NameFinder onChange={updateKeywords} dataList={data}/>
          </div>
        </div>

        <div className="query-row">
          <div className="query-item">
            <div className="query-item">
              <BooleanCheckbox onChange={updateTS}/>
              <div>镰刀给爷死</div>
            </div>

            <div className="query-item">
              <BooleanCheckbox onChange={updateTP}/>
              <div>镐子给爷死</div>
            </div>

            <div className="query-item">
              <BooleanCheckbox onChange={updateTH}/>
              <div>爆破锤给爷死</div>
            </div>
          </div>
        </div>

      </div>
      <div>
        <Table dataSource={result} columns={columns} pagination={false}/>
      </div>
    </div>
  )
}

export default App
